package com.xxrl.hmwork.commons;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.*;

import java.io.File;

/**
 * @author mis
 */
@Component("mailUtils")
public class MailUtils {
    private Logger logger = LoggerFactory.getLogger(MailUtils.class);

    @Value("${spring.mail.username}")
    private String emailFrom;

    private final JavaMailSender javaMailSender;

    public MailUtils(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    /**
     * 发送邮件
     * @param type 1: 发文件 2： 发密码
     * @param content 文件的路径/找回的密码
     * @param receiver 接收者
     */
    public void sendMail(int type,String content, String receiver) {
        logger.info("Sending a email to {}",receiver);
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
            helper.setFrom(emailFrom);
            helper.setTo(receiver);
            if (type == 1) {
                helper.setSubject("[交作业啦]:提交作业");
                helper.addAttachment("file",new File(content));
                helper.setText("",true);
            } else if (type == 2) {
                helper.setSubject("[交作业啦]:找回密码");
                helper.setText(content);
            }
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}
